package JMH.day03.atomicboolean;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class TryLockExample {

    private final static Object o = new Object();

    public static void main(String[] args) {

        final TryLock tryLock = new TryLock();
        final List<Object> list = new ArrayList<>();

        for (int i = 0; i < 10; i++) {

            new Thread(() -> {

                while (true) {
                    try {
                        if (tryLock.lock()) { // 获取锁，而且并不会让线程处于阻塞
                            System.out.println(Thread.currentThread().getName() + ": get the lock");
                            if (list.size() > 1) {
                                System.out.println("111111111111111111111111111111111111111111111");
                                throw new IllegalStateException("fail");
                            }
                            list.add(o);
                        }
                        TimeUnit.MILLISECONDS.sleep(20);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (tryLock.release()) { // 释放锁
                            System.out.println(Thread.currentThread().getName() + ": release the lock");
                            list.remove(o);
                        }
                    }
                }

            }).start();

        }

    }

}
